package com.crlui.manager
{
	import com.crlui.core.IRenderable;
	
	import flash.display.Stage;
	import flash.events.Event;

	public class RenderManager
	{
		private var list:Vector.<IRenderable>;
		
		private var _stage:Stage;
		public static var instance:RenderManager=new RenderManager();
		
		public function RenderManager()
		{
			list=new Vector.<IRenderable>();
		}
		
		public function set stage(value:Stage):void{
			_stage=value;
		}
		
		
		public static function add(value:IRenderable):Boolean{
			return instance.add(value);
		}
		
		public function add(value:IRenderable):Boolean{
			if(list.indexOf(value) !=-1){
				return false;
			}
			
			list.push(value);
			
			if(list.length==1){
				_stage.addEventListener(Event.RENDER,render);
				_stage.invalidate();
			}
			return true;
		}
		
		public function remove(value:IRenderable):Boolean{
			var index:int=list.indexOf(value);
			if(index ==-1){
				return false;
			}
			
			list.splice(index,1);
			return true;
		}
		
		public function render(event:Event):void{

			_stage.removeEventListener(Event.RENDER,render);
			
			var renderList:Vector.<IRenderable>=list.splice(0,list.length);
			for each(var item:IRenderable in renderList){
				item.render();
			}
			
		}
		
	}
}